<!-- 发布作品页面 -->
<template>
  <view class="create-page">
    <!-- 表单区域 -->
    <view class="form-item">
      <text class="label">作品名称*</text>
      <input
        class="input"
        type="text"
        v-model="form.name"
        placeholder="请填写作品名称"
      />
    </view>

    <view class="form-item">
      <text class="label">作品描述*</text>
      <textarea
        class="textarea"
        v-model="form.description"
        placeholder="请填写作品描述"
        rows="3"
      />
    </view>

    <view class="form-item">
      <text class="label">交易价格*</text>
      <input
        class="input"
        type="number"
        v-model="form.price"
        placeholder="请填写交易价格"
      />
    </view>

    <view class="form-item">
      <text class="label">版号数量*</text>
      <input
        class="input"
        type="number"
        v-model="form.quantity"
        placeholder="请填写作品数量"
      />
    </view>

    <view class="form-item" @click="chooseType">
      <text class="label">作品类型*</text>
      <view>
        <block v-if="form.type">
          <view class="chip">
            <image :src="selectedTypeObj?.icon" class="chip-icon" />
            <text class="chip-label">{{ form.type }}</text>
            <text class="chip-close" @click.stop="clearType">×</text>
          </view>
        </block>
        <block v-else>
          <view class="placeholder">请选择作品类型</view>
        </block>
      </view>
    </view>

    <view class="form-item" @click="chooseAttr">
      <text class="label">作品属性</text>
      <view>
        <block v-if="form.attribute.length">
          <view class="chip" v-for="(tag, idx) in form.attribute" :key="idx">
            <text class="chip-label">{{ tag }}</text>
            <text class="chip-close" @click.stop="removeAttr(idx)">×</text>
          </view>
        </block>
        <block v-else>
          <view class="placeholder">请选择作品属性</view>
        </block>
      </view>
    </view>

    <view class="form-item">
      <text class="label">发行版号*</text>
      <view class="edition-box">
        <button
          class="edition-btn"
          :class="{ active: form.edition === 'single' }"
          @click="form.edition = 'single'"
        >
          单版号
        </button>
        <button class="edition-btn disabled" disabled>多版号</button>
      </view>
    </view>

    <view class="form-item">
      <text class="label">作品图*</text>
      <view class="image-wrapper">
        <block v-if="form.image.length === 0">
          <view class="placeholder-box" @click="selectImage">
            <text class="plus">+</text>
          </view>
        </block>
        <block v-else>
          <image :src="form.image[0]" class="preview" mode="aspectFill" />
          <view class="delete-btn" @click="removeImage">×</view>
        </block>
      </view>
    </view>

    <view class="form-item" @click="chooseChain">
      <text class="label">发行区块链*</text>
      <view>
        <block v-if="form.chain">
          <view class="chip">
            <image :src="selectedChainObj?.icon" class="chip-icon" />
            <text class="chip-label">{{ form.chain }}</text>
            <text class="chip-close" @click.stop="clearChain">×</text>
          </view>
        </block>
        <block v-else>
          <view class="placeholder">请选择发行区块链</view>
        </block>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button class="submit-btn" :disabled="!canSubmit" @click="submit">
      提交进行审核发行
    </button>

    <!-- 自定义弹层：作品类型 -->
    <view
      v-if="showTypePopup"
      class="overlay"
      @click.self="showTypePopup = false"
    >
      <view class="sheet">
        <view class="sheet-title">请选择作品类型</view>
        <view
          v-for="(item, idx) in typeOptionsDetailed"
          :key="idx"
          class="sheet-item"
          @click="selectType(item)"
        >
          <image :src="item.icon" class="sheet-icon" />
          <text class="sheet-label">{{ item.label }}</text>
          <text class="arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 自定义弹层：区块链 -->
    <view
      v-if="showChainPopup"
      class="overlay"
      @click.self="showChainPopup = false"
    >
      <view class="sheet">
        <view class="sheet-title">请选择发行区块链</view>
        <view
          v-for="(item, idx) in chainOptionsDetailed"
          :key="idx"
          class="sheet-item"
          @click="selectChain(item)"
        >
          <image :src="item.icon" class="sheet-icon" />
          <text class="sheet-label">{{ item.label }}</text>
          <text class="arrow">›</text>
        </view>
      </view>
    </view>

    <!-- 自定义属性弹层 -->
    <view
      v-if="showAttrPopup"
      class="attr-overlay"
      @click.self="showAttrPopup = false"
    >
      <view class="attr-sheet">
        <view class="attr-input">
          <input v-model="newAttr" placeholder="请输入自定义属性" />
        </view>
        <view class="attr-btn-row">
          <button class="attr-btn attr-cancel" @click="cancelCustomAttr">
            取消
          </button>
          <button class="attr-btn attr-confirm" @click="confirmCustomAttr">
            确定
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from "vue";
import { http } from "@/pages/utils/Http";

interface FormState {
  name: string;
  description: string;
  price: string;
  quantity: string;
  type: string;
  attribute: string[];
  edition: "single" | "";
  image: string[];
  chain: string;
}

const form = ref<FormState>({
  name: "",
  description: "",
  price: "",
  quantity: "",
  type: "",
  attribute: [],
  edition: "single",
  image: [],
  chain: "",
});

// 记录已选对象（带图标）
const selectedTypeObj = ref<any>(null);
const selectedChainObj = ref<any>(null);

// 选项数据（含图标）
const typeOptionsDetailed = [
  { label: "艺术", value: "艺术", icon: "/static/images/3.png" },
  { label: "元宇宙", value: "元宇宙", icon: "/static/images/1.png" },
  { label: "音乐", value: "音乐", icon: "/static/images/2.png" },
  { label: "数字作品", value: "数字作品", icon: "/static/images/4.png" },
  { label: "体育", value: "体育", icon: "/static/images/5.png" },
  { label: "星座", value: "星座", icon: "/static/images/5.png" },
  { label: "虚拟世界", value: "虚拟世界", icon: "/static/images/1.png" },
  { label: "交易品", value: "交易品", icon: "/static/images/7.png" },
  { label: "收藏品", value: "收藏品", icon: "/static/images/8.png" },
  { label: "公益", value: "公益", icon: "/static/images/9.png" },
];

const attrOptionsRecommend = [
  "背景",
  "脸",
  "帽子",
  "身体",
  "其他配件",
  "衣服",
  "动物",
];

const chainOptionsDetailed = [
  { label: "所有链区", value: "all", icon: "/static/images/alllink.png" },
  { label: "腾讯至信链", value: "trustsql", icon: "/static/images/link1.png" },
  { label: "百度超级链", value: "xuper", icon: "/static/images/link2.png" },
  { label: "阿里蚂蚁链", value: "antchain", icon: "/static/images/link3.png" },
];

// 弹层显示状态
const showTypePopup = ref(false);
const showChainPopup = ref(false);
const showAttrPopup = ref(false);

const chooseType = () => {
  showTypePopup.value = true;
};

const selectType = (item: any) => {
  form.value.type = item.label;
  selectedTypeObj.value = item;
  showTypePopup.value = false;
};

// 自定义属性弹层
const newAttr = ref("");

const chooseAttr = () => {
  // 微信 ActionSheet 不支持添加输入框，因此先让用户选择推荐或进入自定义
  uni.showActionSheet({
    itemList: [...attrOptionsRecommend, "自定义..."],
    success: (res) => {
      if (res.tapIndex === attrOptionsRecommend.length) {
        // 打开自定义输入半模态
        newAttr.value = "";
        showAttrPopup.value = true;
        return;
      }
      const tag = attrOptionsRecommend[res.tapIndex];
      addAttr(tag);
    },
  });
};

const addAttr = (tag: string) => {
  if (form.value.attribute.includes(tag)) {
    uni.showToast({ title: "已存在该属性", icon: "none" });
    return;
  }
  if (form.value.attribute.length >= 5) {
    uni.showToast({ title: "最多选择5个属性", icon: "none" });
    return;
  }
  form.value.attribute.push(tag);
};

const confirmCustomAttr = () => {
  const tag = newAttr.value.trim();
  if (!tag) return;
  addAttr(tag);
  showAttrPopup.value = false;
};

const cancelCustomAttr = () => {
  showAttrPopup.value = false;
};

const chooseChain = () => {
  showChainPopup.value = true;
};

const selectChain = (item: any) => {
  form.value.chain = item.label;
  selectedChainObj.value = item;
  showChainPopup.value = false;
};

/**
 * 将本地临时文件读取为 base64 字符串
 * 兼容小程序 / App，H5 环境降级使用 FileReader
 */
const convertToBase64 = (filePath: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    // @ts-ignore getFileSystemManager 仅在微信/小程序/App 可用
    if (typeof uni.getFileSystemManager === "function") {
      // 小程序 / App
      uni.getFileSystemManager().readFile({
        filePath,
        encoding: "base64",
        success: (res: any) => {
          // 根据文件后缀推断 mimeType
          const ext = filePath
            .substring(filePath.lastIndexOf(".") + 1)
            .toLowerCase();
          const mime = ext === "jpg" || ext === "jpeg" ? "jpeg" : ext; // 默认保持原后缀
          resolve(`data:image/${mime};base64,${res.data}`);
        },
        fail: reject,
      });
    } else {
      // H5 环境，使用 XMLHttpRequest + FileReader 读取
      try {
        const xhr = new XMLHttpRequest();
        xhr.open("GET", filePath, true);
        xhr.responseType = "blob";
        xhr.onload = () => {
          const reader = new FileReader();
          reader.onloadend = () => resolve(reader.result as string);
          reader.onerror = reject;
          reader.readAsDataURL(xhr.response);
        };
        xhr.onerror = reject;
        xhr.send();
      } catch (error) {
        reject(error);
      }
    }
  });
};

// 选择图片并转换为 base64
const selectImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ["compressed"],
    success: async (res) => {
      try {
        const base64 = await convertToBase64(res.tempFilePaths[0]);
        form.value.image = [base64];
      } catch (e) {
        uni.showToast({ title: "图片读取失败", icon: "none" });
      }
    },
  });
};

const removeImage = () => {
  form.value.image = [];
};

// 提交可用性
const canSubmit = computed(() => {
  const f = form.value;
  return (
    f.name &&
    f.description &&
    f.price &&
    f.quantity &&
    Number(f.quantity) > 0 &&
    f.type &&
    f.image.length &&
    f.chain
  );
});

// 提交逻辑
const submit = async () => {
  if (!canSubmit.value) return;
  try {
    uni.showLoading({ title: "提交中..." });

    // 构建提交数据
    const payload = {
      userId: uni.getStorageSync("userId"),
      name: form.value.name,
      description: form.value.description,
      price: Number(form.value.price),
      type: form.value.type,
      total_edition: Number(form.value.quantity),
      image: form.value.image[0],
      chain: form.value.chain,
      attributes: form.value.attribute,
    };

    const res = await http.post<any>("/api/works", payload);

    uni.hideLoading();

    if (res.code === 200) {
      uni.showToast({ title: res.message || "提交成功", icon: "success" });
      // 重置表单
      form.value = {
        name: "",
        description: "",
        price: "",
        quantity: "",
        type: "",
        attribute: [],
        edition: "single",
        image: [],
        chain: "",
      };
      selectedTypeObj.value = null;
      selectedChainObj.value = null;
    } else {
      uni.showToast({ title: res.message || "提交失败", icon: "none" });
    }
  } catch (err: any) {
    uni.hideLoading();
    uni.showToast({ title: err?.message || "提交失败", icon: "none" });
  }
};

// 清除函数
const clearType = () => {
  form.value.type = "";
  selectedTypeObj.value = null;
};

const clearChain = () => {
  form.value.chain = "";
  selectedChainObj.value = null;
};

const removeAttr = (index: number) => {
  form.value.attribute.splice(index, 1);
};
</script>

<style scoped lang="scss">
.create-page {
  padding: 24rpx;
  background-color: #f7f8fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.form-item {
  background: #fff;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;

  .label {
    font-size: 26rpx;
    color: #111;
    margin-left: 20rpx;
    margin-bottom: 8rpx;
  }

  .input,
  .textarea {
    padding: 0 20rpx;
    font-size: 26rpx;
    border: none;
  }

  .textarea {
    width: 100%;
    box-sizing: border-box;
  }

  .placeholder {
    color: #aaa;
    font-size: 26rpx;
    padding: 0 20rpx;
  }

  .value {
    color: #111;
    font-size: 26rpx;
    padding: 0 20rpx;
  }

  .edition-box {
    display: flex;
    gap: 20rpx;
    padding: 0 20rpx;

    .edition-btn {
      flex: none;
      padding: 12rpx 36rpx;
      border-radius: 12rpx;
      font-size: 26rpx;
      border: 1rpx solid #6f76fb;
      background-color: #fff;
      color: #6f76fb;

      &.active {
        background-color: #6f76fb;
        color: #fff;
      }

      &.disabled {
        opacity: 0.4;
      }
    }
  }

  .chip {
    display: inline-flex;
    align-items: center;
    background: #f1f1f1;
    border-radius: 8rpx;
    padding: 4rpx 10rpx;
    margin-left: 20rpx;

    .chip-icon {
      width: 28rpx;
      height: 28rpx;
      margin-right: 8rpx;
      border-radius: 4rpx;
    }

    .chip-label {
      font-size: 24rpx;
      margin-right: 8rpx;
    }

    .chip-close {
      font-size: 24rpx;
      color: #999;
      cursor: pointer;
    }
  }
}

.submit-btn {
  width: 100%;
  margin-top: 40rpx;
  background-color: #6f76fb;
  color: #fff;
  border: none;
  border-radius: 12rpx;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 30rpx;

  &[disabled] {
    background-color: #ccc;
  }
}

.image-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 0 20rpx;

  .placeholder-box {
    width: 100%;
    height: 100rpx;
    background-color: #eee;
    border-radius: 12rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;

    .plus {
      font-size: 40rpx;
      color: #6f76fb;
    }
  }

  .preview {
    width: 100rpx;
    height: 100rpx;
    border-radius: 12rpx;
  }

  .delete-btn {
    font-size: 30rpx;
    color: #6f76fb;
    cursor: pointer;
  }
}

.overlay {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;
}

.sheet {
  width: 100%;
  background: #fff;
  border-top-left-radius: 16rpx;
  border-top-right-radius: 16rpx;
  max-height: 70vh;
  overflow-y: auto;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .sheet-title {
    text-align: center;
    font-size: 30rpx;
    padding: 24rpx 0;
    font-weight: 600;
    color: #333;
  }

  .sheet-item {
    display: flex;
    align-items: center;
    padding: 24rpx 32rpx;
    border-bottom: 1px solid #f1f1f1;

    .sheet-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 24rpx;
    }

    .sheet-label {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }

    .arrow {
      font-size: 32rpx;
      color: #bbb;
    }
  }
}

.attr-overlay {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;
}

.attr-sheet {
  width: 100%;
  background: #fff;
  border-top-left-radius: 16rpx;
  border-top-right-radius: 16rpx;
  padding: 40rpx 32rpx;
}

.attr-input {
  width: 100%;
  background: #f7f7f7;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
}

.attr-btn-row {
  margin-top: 32rpx;
  display: flex;
  gap: 24rpx;
}

.attr-btn {
  flex: 1;
  height: 72rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.attr-cancel {
  background: #eee;
  color: #333;
}
.attr-confirm {
  background: #6f76fb;
  color: #fff;
}
</style>
